<template>
  <div class="list-table">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('文件')" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          :placeholder="$t('文件')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item v-show="!externalCallTemplateStatus" :label="$t('模板类型')" prop="templateType">
        <el-select v-model="queryParams.templateType" style="width: 100%;" :placeholder="$t('请选择')">
          <el-option
            v-for="dict in templateTypeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button v-show="!externalCallTemplateStatus" icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row v-show="!externalCallTemplateStatus" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:word:edit']"
          type="warning"
          icon="el-icon-plus"
          size="mini"
          @click="uploadWordHandle"
        >{{ $t('上传') }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-if="officeSwitchStatus"
          v-hasPermi="['system:word:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="openWordHandle"
        >{{ $t('新增') }}</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:word:edit']"
          type="success"
          icon="el-icon-video-play"
          size="mini"
          @click="paramsCustomHandler"
        >{{ $t('自定义参数') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip :content="$t('使用: 前往自定义模板数据集进行关键字维护, word中以${关键字}形式生成文档!')" placement="top">
          <i class="el-icon-question" style="margin-top: 6px;" />
        </el-tooltip>
      </el-col>
    </el-row>

    <!--
    Call款和分配冲突注释掉了
    <el-row v-show="externalCallTemplateStatus && (wordOnlineTemplateList === undefined || wordOnlineTemplateList === null || wordOnlineTemplateList.length <= 0)" :gutter="10" style="margin-left: -5px;margin-right: -5px;padding-top: 35px;margin-bottom: -35px;">
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          @click="generateBuiltInCallTemplate"
        >{{ $t('生成内置Call款模板') }}</el-button>
      </el-col>
    </el-row>
    -->

    <el-table v-loading="loading" :data="wordOnlineTemplateList" border :style="{ 'margin-top': !externalCallTemplateStatus ? '0px' : '50px' }">
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('文件')" align="center" prop="fileName">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="onlinePreviewOnlineEdit('view', scope.row)">
            {{ $t(scope.row.fileName) }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('模板编码')" align="center" prop="templateType" show-overflow-tooltip min-width="100" />
      <el-table-column :label="$t('上传人')" align="center" prop="createBy.nickName" />
      <el-table-column :label="$t('上传时间')" align="center" prop="createTime" />
      <el-table-column v-if="!externalCallTemplateStatus" :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="230">
        <template slot-scope="scope">
          <!-- <el-button
            v-if="officeSwitchStatus"
            v-hasPermi="['system:word:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="onlinePreviewOnlineEdit('review', scope.row)"
          >{{ $t('编辑') }}</el-button> -->
          <el-button
            v-hasPermi="['system:word:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="onlinePreviewOnlineEditHandle(scope.row)"
          >{{ $t('编辑') }}</el-button>
          <el-button
            v-hasPermi="['system:word:export']"
            size="small"
            type="text"
            icon="el-icon-setting"
            @click="editHandle(scope.row)"
          >{{ $t('生成') }}</el-button>
          <el-button
            v-hasPermi="['system:word:view']"
            size="small"
            type="text"
            icon="el-icon-download"
            @click="downloadFile(scope.row)"
          >{{ $t('下载') }}</el-button>
          <el-button
            v-hasPermi="['system:word:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
      <el-table-column v-else :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:word:edit']"
            size="small"
            type="text"
            :disabled="choiceTemplateId === scope.row.id"
            icon="el-icon-edit"
            @click="selectedTemplate(scope.row)"
          >{{ $t('选定') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div style="float: right; margin-top: 20px;font-size: 14px;">
      <div v-show="externalCallTemplateStatus" style="float: right;">*{{ $t('前往撰写报告下自定义模板中添加') }}</div><br>
      <div style="float: right; margin-top: 5px;color: red;">{{ $t(textReminder) }}</div>
    </div>

    <!-- 添加或修改word在线模板对话框 -->
    <el-dialog :title="title" :visible.sync="formOpen" width="600px" style="margin-top: 5vh !important;height: 600px !important;" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" custom-class="dialogForm" append-to-body>
      <wordOnlineTemplateForm ref="wordOnlineTemplateForm" />
    </el-dialog>

    <!-- 新增 -->
    <el-dialog :title="title" :visible.sync="newOpen" width="600" style="height: 350px; width: 600px; margin: auto !important;" :close-on-click-modal="false" custom-class="dialogForm" append-to-body>
      <template>
        <div v-loading="newLoading">
          <el-form ref="createForm" :model="createForm" :rules="createFormRules" label-width="120px" class="dataForm">
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('模板类型')" prop="templateType">
                  <el-select v-model="createForm.templateType" style="width: 100%;" :placeholder="$t('请选择')">
                    <el-option
                      v-for="dict in templateTypeOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('文件名称')" prop="file">
                  <el-input v-model="createForm.file" :placeholder="$t('模板类型')" maxlength="25" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: right;">
            <div style="display: inline-block; margin-left: 10px;">
              <el-button @click="cancel">{{ $t('取消') }}</el-button>
              <el-button type="primary" @click="createWordHandle">{{ $t('新建') }}</el-button>
            </div>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 上传 -->
    <el-dialog :title="title" :visible.sync="uploadOpen" width="30%" style="margin: auto !important;" :close-on-click-modal="false" custom-class="" append-to-body>
      <template>
        <div v-loading="uploadLoading">
          <el-form ref="uploadForm" :model="uploadForm" :rules="uploadFormRules" label-width="120px" class="dataForm">
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('模板编码')" prop="templateType">
                  <!-- <el-select v-model="uploadForm.templateType" style="width: 100%;" :placeholder="$t('请选择')">
                    <el-option
                      v-for="dict in templateTypeOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select> -->
                  <el-input v-model="uploadForm.templateType" :placeholder="$t('模板编码')" show-word-limit maxlength="100" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('文件名称')" prop="file">
                  <single
                    v-if="!uploadFileName"
                    ref="singleRef"
                    v-hasPermi="['system:word:edit']"
                    :upload-style="uploadStyle"
                    :upload-btn-name="$t('点击此处上传模板文件')"
                    only-suffix="docx"
                    data-type="insert_key_word_template"
                    @appendData="appendData"
                    @okPostUploadHook="okPostUploadHook"
                  />
                  <el-link v-show="uploadFileName" type="primary" :underline="false" @click="onlinePreviewOnlineEdit('', { fileId: uploadFileId })">{{ uploadFileName }}</el-link>
                  <i v-show="uploadFileName" class="el-icon-circle-close" style="color: #1890ff;margin-left: 15px;cursor: pointer;" @click="uploadFileId = ''; uploadFileName = ''" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('自定义参数')" prop="customParamIdList">
                  <el-select v-model="uploadForm.customParamIdList" style="width: 100%;" multiple :placeholder="$t('请选择')">
                    <el-option
                      v-for="dict in customParamList"
                      :key="dict.id"
                      :label="$t(dict.paramName)"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: right;">
            <div style="display: flex; margin-left: 10px;">
              <el-button style="margin-right: 5px;" @click="cancel">{{ $t('取消') }}</el-button>
              <el-button type="primary" @click="uploadWordHandleSave">{{ $t('上传') }}</el-button>
            </div>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 附件预览 -->
    <OnlinePreview ref="OnlinePreview" preview-type="insert_key_word_template" />
    <el-dialog :title="$t('自定义参数')" :visible.sync="paramsCustomOpen" width="80%" :close-on-click-modal="false" :lock-scroll="false" custom-class="" append-to-body>
      <wordOnlineParamsCustomList ref="wordOnlineParamsCustomList" />
    </el-dialog>
    <div class="online">
      <el-dialog :title="$t('在线编辑')" :visible.sync="onlineEditTemplateOpen" height="98%" width="98%" :close-on-click-modal="false" :lock-scroll="false" custom-class="previewDialog" append-to-body>
        <onlineEditTemplate ref="onlineEditTemplate" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Single from '@/components/File/Upload/single'
import {
  listWordOnlineTemplate,
  delWordOnlineTemplate,
  exportWordOnlineTemplate,
  saveWordOnlineTemplate,
  createWord,
  generateBuiltInTemplate,
  getBusinessWordCustomTemplate
} from '@/api/system/word/template/wordOnlineTemplate.js'
import wordOnlineTemplateForm from './wordOnlineTemplateForm.vue'
import onlineEditTemplate from './onlineEditTemplate'
import { getSysVarValue } from '@/api/system/config'
import { downLoadFileOpen } from '@/utils/zipdownload'
import wordOnlineParamsCustomList from '../wordOnlineParamsCustomList.vue'
import { listWordOnlineParamsCustom } from '@/api/system/word/wordOnlineParamsCustom'
export default {
  components: {
    wordOnlineTemplateForm,
    Single,
    wordOnlineParamsCustomList,
    onlineEditTemplate
  },
  data() {
    var checkFileName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(this.$t('请输入文件名称')))
      } else {
        var reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,25}$/
        if (!reg.test(value)) {
          callback(new Error(this.$t('文件名不规则!')))
        } else {
          callback()
        }
      }
    }
    const checkFile = (rule, value, callback) => {
      // if (rule === value) {}
      if (this.uploadFileId === '' || this.uploadFileId === undefined || this.uploadFileId === null) {
        return callback(new Error(this.$t('请添加文件')))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // word在线模板表格数据
      wordOnlineTemplateList: [],
      // 弹出层标题
      title: this.$t('生成模板'),
      // 是否显示弹出层
      formOpen: false,
      paramsCustomOpen: false,
      uploadOpen: false,
      newOpen: false,
      newLoading: false,
      uploadLoading: false,
      onlineEditTemplateOpen: false,
      // 查询参数
      queryParams: {
        fileName: undefined,
        templateType: undefined,
        type: undefined,
        businessName: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      createForm: {
        templateType: undefined,
        file: undefined
      },
      uploadForm: {
        templateType: undefined,
        file: undefined
      },
      templateTypeOptions: [],
      // 表单校验
      rules: {},
      officeSwitchStatus: undefined,
      createFormRules: {
        templateType: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
        file: [{ required: true, validator: checkFileName, trigger: ['blur', 'change'] }]
      },
      uploadFormRules: {
        templateType: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
        file: [{ required: true, validator: checkFile, trigger: ['blur', 'change'] }]
      },
      uploadFileId: '',
      uploadFileName: '',
      // 外部调用模板状态, 例如call调用这里
      externalCallTemplateStatus: false,
      // 右下角的文字提示
      textReminder: '',
      uploadStyle: 'border: none; font-size: 14px; color: #8d9092;text-decoration:underline',
      choiceTemplateId: '',
      customParamList: []
    }
  },
  created() {
    this.getList()
    this.getOfficeSwitch()
    this.getCustomParamList()
    // 模板类型
    this.getDicts('custom_template_type').then(response => {
      this.templateTypeOptions = response.data
    })
  },
  methods: {
    /** 查询word在线模板列表 */
    getList() {
      this.loading = true
      listWordOnlineTemplate(this.queryParams).then(response => {
        this.wordOnlineTemplateList = response.rows
        this.total = response.total
        // 获取选中的那条
        if (this.$route.query.id) {
          getBusinessWordCustomTemplate(this.$route.query.id, this.queryParams.templateType).then(response => {
            if (response.data !== null) {
              this.choiceTemplateId = response.data.templateId
            }
            this.loading = false
          })
        } else {
          this.loading = false
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fileId: undefined,
        type: undefined,
        businessId: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    formatTemplateType(row) {
      return this.selectDictLabel(this.templateTypeOptions, row.templateType)
    },
    getCustomParamList() {
      listWordOnlineParamsCustom({}).then(response => {
        this.customParamList = response.rows
      })
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryHandle()
    },
    /** 打开新增文件 **/
    openWordHandle() {
      this.title = this.$t('创建模板')
      this.createForm.templateType = undefined
      this.createForm.file = undefined
      this.uploadLoading = false
      this.newOpen = true
    },
    /** 打开上传文件窗口 */
    uploadWordHandle() {
      this.title = this.$t('上传模板')
      this.uploadForm.templateType = undefined
      this.uploadForm.file = undefined
      this.uploadFileId = ''
      this.uploadFileName = ''
      this.newLoading = false
      this.uploadOpen = true
    },
    /** 新增空白模板文件docx */
    createWordHandle() {
      console.log('新增模板')
      this.$refs['createForm'].validate(valid => {
        if (valid) {
          this.newLoading = true
          createWord(this.createForm.templateType, this.createForm.file).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t(response.msg))
            } else {
              this.msgError(this.$t('创建失败!'))
            }
            this.newOpen = false
            this.newLoading = false
            this.getList()
          })
        }
      })
    },
    /** 关闭窗口 */
    cancel() {
      this.newOpen = false
      this.uploadOpen = false
    },
    /** 编辑按钮操作 */
    editHandle(row) {
      this.formOpen = true
      this.title = this.$t('生成模板') + ': ' + this.$t(row.fileName)
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.wordOnlineTemplateForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delWordOnlineTemplate(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return exportWordOnlineTemplate(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    // 预览附件
    onlinePreviewOnlineEdit(type, row) {
      this.$refs.OnlinePreview.onlinePreviewFile(row.fileId, type)
    },
    // 下载附件
    downloadFile(row) {
      downLoadFileOpen(row.fileId)
    },
    /** 上传文件按钮 **/
    uploadWordHandleSave() {
      this.$refs['uploadForm'].validate(valid => {
        if (valid) {
          this.uploadLoading = true
          saveWordOnlineTemplate({ fileId: this.uploadFileId, templateType: this.uploadForm.templateType, customParamIdList: this.uploadForm.customParamIdList }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
            } else {
              this.msgError(response.msg)
            }
            this.uploadLoading = false
            this.cancel()
            this.getList()
          })
        }
      })
    },
    /**
     * 先把旧文件 放到文件历史中.
     * 新文件的 url, name, real_name, md5, suffix, sizes 字段
     * 放到旧文件, ,删掉新文件
     * @param data
     */
    appendData(data) {
      console.log(data)
      this.uploadFileName = data.fileName || data.name
      this.uploadFileId = data.fileId || data.id
      this.uploadLoading = false
    },
    // windows上传窗口点击确定后执行以下代码
    okPostUploadHook() {
      this.uploadLoading = true
    },
    // 选定模板 调用父页面方法
    selectedTemplate(row) {
      this.$emit('saveSelectTemplate', this, row)
    },
    // 生成Call款内置模板
    generateBuiltInCallTemplate() {
      var that = this
      this.$confirm(that.$t('将生成一个系统内置的模板,是否继续?'), that.$t('提示'), {
        confirmButtonText: that.$t('确定'),
        cancelButtonText: that.$t('取消'),
        type: 'warning'
      }).then(function() {
        that.loading = true
        generateBuiltInTemplate('call').then(response => {
          console.log(response)
          that.loading = false
          that.queryHandle()
        })
      }).catch(function() {
      })
    },
    getOfficeSwitch() {
      getSysVarValue('office.changxie.enabled').then(response => {
        this.officeSwitchStatus = (response.data.office_changxie_enabled === 'true')
      })
    },
    paramsCustomHandler() {
      this.paramsCustomOpen = true
      this.$nextTick(() => {
        this.$refs.wordOnlineParamsCustomList.getList()
      })
    },
    onlinePreviewOnlineEditHandle(row) {
      this.onlineEditTemplateOpen = true
      this.$nextTick(() => {
        this.$refs.onlineEditTemplate.init(row.fileId)
      })
      // const { href } = this.$router.resolve({ path: '/template/onlineEdit',
      // query: { fileId: row.fileId }})
      // window.open(href, '_blank')
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
